package com.sduept.nwld.dataserver.controller.message;

import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.component.message.model.MessageTypeDTO;
import com.sduept.component.message.model.PersonnelConfigure;
import com.sduept.component.message.model.PersonnelMsgConfigureDTO;
import com.sduept.generator.ObjectId;
import com.sduept.message.entity.MessageReceiveConfig;
import com.sduept.message.entity.MessageType;
import com.sduept.message.manager.MessageReceiveConfigManager;
import com.sduept.message.manager.MessageTypeManager;
import com.sduept.nwld.dataserver.manager.message.MessageReceiverManager;
import com.sduept.nwld.dataserver.manager.message.PersonnelMessageConfigureManager;
import com.sduept.nwld.dataserver.manager.message.PersonnelMsgConfigureDTOManager;
import com.sduept.nwld.dataserver.model.library.MessageReceiver;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.permission.entity.PersonnelEntityBean;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.event.ValueChangeEvent;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.sql.SQLException;
import java.util.*;

@Named
@ViewScoped
public class MobileMessConfigController extends AbstractController {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6448797125465701056L;
	@Autowired
	private PersonnelMsgConfigureDTOManager ma;
	@Autowired
	private MessageTypeManager typeManager;
	@Autowired
	private PersonnelMessageConfigureManager personMa;
	@Autowired
	private MessageReceiverManager recMa;
	@Autowired
	private MessageReceiveConfigManager relation;

	private List<MessageTypeDTO> allTypeList = new ArrayList<MessageTypeDTO>();
	private TreeNode root;
	private PersonnelMsgConfigureDTO dto = null; // 个人和推送类型和是否推送的对应关系
	private PersonnelEntityBean user = null; // 当前登陆人
	private PersonnelConfigure person; // 人员的消息，4A账户/通讯地址等

	private List<String> recString = new ArrayList<String>();// 接收方式的中文描述
	private Map<String, String> map = new HashMap<String, String>(); // 接收方式的id和中文描述对应MAP

	private String receiveChangeValue = null; // 指示当前操作是增加还是删除
	private boolean editShow = false;// 4A账户等人员信息是否能被编辑
	private int countRoot = 0;

	@PostConstruct
	private void init() {
		user = getCurrentUser();
		if (user != null) {
			dto = ma.getByConfigureId(user.getId());
			person = dto.getConfigure();
			if (person == null) {
				synchronizePerson();
			}
			List<MessageReceiver> recTypes = recMa.listAll();
			for (MessageReceiver r : recTypes) {
				recString.add(r.getId());
			}
			initMap();
			getAlltype();
			initTable();
			countRoot = typeManager.findRoots().size();
		} else {
			addErrorMessage("请先登录！");
		}
	}

	/**
	 * 同步人员信息（将当前登陆用户的信息，同步给用户的4A账户）
	 */
	private void synchronizePerson() {
		person = new PersonnelConfigure();
		person.setAccount("");
		person.setId(user.getId());
		person.setCode(user.getCode());
		person.setName(user.getName());
		person.setRealName(user.getName());
	}

	/**
	 * 获取所有的消息类型
	 */
	private void getAlltype() {
		List<MessageType> allType = typeManager.findAll();
		allTypeList.clear();
		if (allType != null) {
			for (MessageType m : allType) {
				MessageTypeDTO n = new MessageTypeDTO();
				n.setMsgType(m);
				allTypeList.add(n);
			}
		}
	}

	/**
	 * 加载table
	 */
	public void initTable() {
		root = new LibTreeNode("treeRoot", null);
		dto = ma.getByConfigureId(user.getId());
		List<MessageTypeDTO> messageTypeList = dto.getDtos();
		for (MessageTypeDTO type : allTypeList) {
			List<MessageReceiver> m = new ArrayList<MessageReceiver>();
			for (MessageTypeDTO me : messageTypeList) {
				if (StringUtils.isNotEmpty(type.getMsgType().getId()) && type.getMsgType().getId().equals(me.getMsgType().getId())) {
					m = me.getReceivers();
					break;
				}
			}
			String[] temp = new String[m.size()];
			for (int i = 0; i < m.size(); i++) {
				MessageReceiver me = m.get(i);
				temp[i] = me.getId();
			}
			type.setRec(temp);
		}
		for (MessageTypeDTO type : allTypeList) {
			if (StringUtils.isEmpty(type.getMsgType().getPid())) {
				TreeNode baseNode = new LibTreeNode(type, root);
				baseNode.setExpanded(true);
				getSunNode(type.getMsgType().getId(), baseNode);
			}
		}
	}

	/**
	 * 保存用户的账户信息
	 */
	public void savePerson() {
		person = personMa.save(person);
		editShow = !editShow;
		addSuccessMessage("基本信息保存成功！");
	}

	/**
	 * 用户单个修改接收状态
	 * 
	 * @param m
	 */
	public void saveConfig(MessageTypeDTO m) {
		String pid = m.getMsgType().getPid();
		String changeValue = receiveChangeValue.substring(4);
		List<MessageReceiveConfig> relaitions = relation.findByCondition(user.getCode(), changeValue, pid);
		if (receiveChangeValue.contains("add_")) {
			List<MessageType> types = typeManager.findTypeByPid(pid);
			List<MessageType> typeList = new ArrayList<MessageType>();
			typeList.add(m.getMsgType());
			if (types.size() - relaitions.size() == 1) {
				typeList.add(typeManager.findTypeById(pid));
			}
			List<MessageReceiveConfig> relationSaveList = new ArrayList<MessageReceiveConfig>();
			for (MessageType e : typeList) {
				MessageReceiveConfig relation = new MessageReceiveConfig();
				relation.setId(ObjectId.get().toString());
				relation.setReceiverId(user.getCode());
				relation.setMsgSenderId(changeValue);
				relation.setMsgTypeId(e.getId());
				relationSaveList.add(relation);
			}
			try {
				relation.save(relationSaveList);
			} catch (SQLException e1) {

				e1.printStackTrace();
				addErrorMessage("保存失败！");
			}
		} else if (receiveChangeValue.contains("del_")) {
			if (relaitions.size() == 1) {
				relation.deleteByCondition(user.getCode(), changeValue, pid);
			} else {
				relation.delete(user.getCode(), m.getMsgType().getId(), changeValue);
			}
		}
		initTable();
	}

	/**
	 * 用户批量修改接收状态（一组）
	 * 
	 * @param m
	 */
	public void saveListConfig(MessageTypeDTO m) {
		String pid = m.getMsgType().getId();
		String changeValue = receiveChangeValue.substring(4);
		if (receiveChangeValue.contains("add_")) {
			relation.deleteByCondition(user.getCode(), changeValue, pid);
			List<MessageType> typeList = typeManager.findTypeByPid(pid);
			typeList.add(typeManager.findTypeById(pid));
			List<MessageReceiveConfig> relationSaveList = new ArrayList<MessageReceiveConfig>();
			for (MessageType e : typeList) {
				MessageReceiveConfig relation = new MessageReceiveConfig();
				relation.setId(ObjectId.get().toString());
				relation.setReceiverId(user.getCode());
				relation.setMsgSenderId(changeValue);
				relation.setMsgTypeId(e.getId());
				relationSaveList.add(relation);
			}
			try {
				relation.save(relationSaveList);
			} catch (SQLException e1) {

				e1.printStackTrace();
				addErrorMessage("保存失败！");
			}
		} else if (receiveChangeValue.contains("del_")) {
			relation.deleteByCondition(user.getCode(), changeValue, pid);
		}
		initTable();
	}

	/**
	 * 接收并转换change类型
	 * @param event
	 */
	public void receiveChangeValue(ValueChangeEvent event) {
		receiveChangeValue = "";
		for (String o : (String[]) event.getNewValue()) {
			/*
			 * 筛选出两个数组中相同的值，>= 0 表示相同，< 0 表示不同 。 有相同值是返回元素的下标值。 此处采用的是 "二分搜索法来搜索指定数组"。
			 */
			if (Arrays.binarySearch((String[]) event.getOldValue(), o) < 0) {
				receiveChangeValue = "add_" + o;
			}
		}
		if (StringUtils.isEmpty(receiveChangeValue)) {
			for (String o : (String[]) event.getOldValue()) {
				if (Arrays.binarySearch((String[]) event.getNewValue(), o) < 0) {
					receiveChangeValue = "del_" + o;
				}
			}
		}
	}

	/**
	 * 根据id获取接收方式的中文描述对应
	 * @param id
	 * @return
	 */
	public String getStr(String id) {
		return map.get(id);
	}

	public void showEdit() {
		editShow = !editShow;
	}

	private void getSunNode(String pid, TreeNode baseNode) {
		for (MessageTypeDTO subtype : allTypeList) {
			if (pid != null && pid.equals(subtype.getMsgType().getPid())) {
				TreeNode subNode = new DefaultTreeNode(subtype, baseNode);
				subNode.setExpanded(true);
			}
		}
	}

	private Map<String, String> initMap() {
		List<MessageReceiver> list = recMa.listAll();
		for (MessageReceiver m : list) {
			map.put(m.getId(), m.getName());
		}
		return map;
	}

	public PersonnelMsgConfigureDTO getDto() {
		return dto;
	}

	public void setDto(PersonnelMsgConfigureDTO dto) {
		this.dto = dto;
	}

	public TreeNode getRoot() {
		return root;
	}

	public void setRoot(TreeNode root) {
		this.root = root;
	}

	public PersonnelConfigure getPerson() {
		return person;
	}

	public void setPerson(PersonnelConfigure person) {
		this.person = person;
	}

	public PersonnelEntityBean getUser() {
		return user;
	}

	public void setUser(PersonnelEntityBean user) {
		this.user = user;
	}

	public List<MessageTypeDTO> getAllTypeList() {
		return allTypeList;
	}

	public void setAllTypeList(List<MessageTypeDTO> allTypeList) {
		this.allTypeList = allTypeList;
	}

	public List<String> getRecString() {
		return recString;
	}

	public void setRecString(List<String> recString) {
		this.recString = recString;
	}

	public boolean isEditShow() {
		return editShow;
	}

	public void setEditShow(boolean editShow) {
		this.editShow = editShow;
	}

	public int getCountRoot() {
		return countRoot;
	}

	public void setCountRoot(int countRoot) {
		this.countRoot = countRoot;
	}

}
